<?php
$dbms='mysql';     //数据库类型
$host='localhost'; //数据库主机名
$dbName='chuanshuo';    //使用的数据库
$user='root';      //数据库连接用户名
$pass='chuanshuo888';          //对应的密码
$dsn="$dbms:host=$host;dbname=$dbName";


$cai = 2;
$cai_again = null;


$cai = isset($_POST['cai']) ? htmlspecialchars($_POST['cai']) : '';
//echo $cai;

//查询赞
if($cai<2){
	try {
		$dbh = new PDO($dsn, $user, $pass); //初始化一个PDO对象
		//echo "连接成功<br/>";
		//你还可以进行一次搜索操作
		$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		foreach ($dbh->query('SELECT * from attitude') as $row) {
			//print_r($row["zan"]); //你可以用 echo($GLOBAL); 来看到这些值
			$zan = $row["zan"];
			$cai = $row["cai"];
		}
		
		$dbh = null;
	} catch (PDOException $e) {
		die ("Error!: " . $e->getMessage() . "<br/>");
	}
	//默认这个不是长连接，如果需要数据库长连接，需要最后加一个参数：array(PDO::ATTR_PERSISTENT => true) 变成这样：
	//$db = new PDO($dsn, $user, $pass, array(PDO::ATTR_PERSISTENT => true));
	$response = $cai;
	echo $response;
}else{
	
	try {
		$dbh = new PDO($dsn, $user, $pass); //初始化一个PDO对象
		//echo "连接成功<br/>";
		//你还可以进行一次搜索操作
		$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		foreach ($dbh->query('SELECT * from attitude') as $row) {
			//print_r($row["zan"]); //你可以用 echo($GLOBAL); 来看到这些值
			$zan = $row["zan"];
			$cai = $row["cai"];
		}
		
		$dbh = null;
	} catch (PDOException $e) {
		die ("Error!: " . $e->getMessage() . "<br/>");
	}

//增加赞
	$cai_again = $cai + 1;
	//print_r($zan_again)；
	try {
		$conn = new PDO("mysql:host=$host;dbname=$dbName", $user, $pass);
		// 设置 PDO 错误模式，用于抛出异常
		$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		$sql = "UPDATE `attitude` SET `cai` = '" . $cai_again . "' WHERE `attitude`.`id` = 0";
		// 使用 exec() ，没有结果返回 
		$conn->exec($sql);
		//echo "新记录插入成功";
	}
	catch(PDOException $e)
	{
		echo $sql . "<br>" . $e->getMessage();
	}

	$response = $cai_again;
	echo $response;
	//echo 55;
}

?>

